package pt.mleiria.bo.dashboard;

import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;
import pt.mleiria.bo.mother.MotherVoiceEJB;

import pt.mleiria.dao.UserDao;
import pt.mleiria.vo.User;

/**
 * @author NB13712
 *
 */
@Stateless
public class LoginEJB {

    private static final Logger LOG = Logger.getLogger(LoginEJB.class);

    @PersistenceContext(unitName = "DomusService")
    private EntityManager em;

    private User user;
    
    @EJB
    private MotherVoiceEJB msEjb;

    public MotherVoiceEJB getMsEjb() {
        return msEjb;
    }

    public boolean isUserAuthenticated(final String username, final String password) {
        try {
            Query q = em
                    .createQuery("select u from UserDao u where u.username = :username and u.password = :password");
            q.setParameter("username", username);
            q.setParameter("password", password);
            UserDao userDao = (UserDao) q.getSingleResult();
            LOG.info("[" + userDao.getUsername() + ";" + userDao.getPassword() + ";" + userDao.getEmail() + "]");
            user = new User(userDao.getUsername(), userDao.getId(), userDao.getName());
            msEjb.sayHelloMother(user.getName());
            return true;
        } catch (NoResultException e) {
            LOG.info("O User:[" + username + "] nao existe");
            LOG.error(e.getMessage());
            return false;
        } catch (Exception e) {
            LOG.error(e.getMessage());
            e.printStackTrace();
            return false;
        }

    }

    public User getUser() {
        return this.user;
    }
    
    
    
    public String[] getAllUserNames(){
        Query q = em.createQuery("select u from UserDao u");
        List<UserDao> list = q.getResultList();
        final String[] nomes = new String[list.size()];
        for(int i = 0; i < list.size(); i++){
            nomes[i] = list.get(i).getName();
        }
        return nomes;
    }
}
